package com.baichang.taoshunda.service.impl;

import com.alipay.api.AppPay;
import com.baichang.framework.excelption.ServiceException;
import com.baichang.framework.model.Page;
import com.baichang.framework.utils.KidUtils;
import com.baichang.taoshunda.dao.*;
import com.baichang.taoshunda.entity.*;
import com.baichang.taoshunda.entity.em.currencyCode;
import com.baichang.taoshunda.entity.em.payHistory;
import com.baichang.taoshunda.service.TrendService;
import com.baichang.taoshunda.service.WaiterlistService;
import com.baichang.taoshunda.weixin.tencent.WeixinUtils;
import com.sun.deploy.util.Waiter;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/8/28 0028.
 */
@Service
public class WaiterlistServiceImpl implements WaiterlistService {

    @Autowired
    private WaiterListDao waiterListDao;

    @Autowired
    private CompanyPanymentHistoryDao companyPanymentHistoryDao;

    @Autowired
    private CityDao cityDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private TrendService trendService;

    /**
     * 查询本地服务商家
     *
     * @param businessName
     * @param typeId
     * @param address
     * @param userId
     * @param nowPage
     * @param pageSize     @return
     */
    @Override
    public List<Map<String, Object>> queryWaiterBusinessList(String businessName, Integer typeId, String address, Integer userId, int nowPage, int pageSize) {
        if (userId > 0) {
            //查询该用户下的正常状态和缴费支付、缴费待支付的服务商家
            List<Map<String, Object>> list = waiterListDao.queryAllUserWaiter(userId);
            for (int i = 0; i < list.size(); i++) {
                int waiterId = Integer.parseInt(list.get(i).get("id").toString());
                //符合上述条件数据的id  查询缴费记录  有为1  无为0
                Map<String, Object> map = companyPanymentHistoryDao.queryUserWaiter(waiterId);
                String num = map.get("num").toString();
                if (num.equals("0")) { //为0  状态改为待支付
                    Map map1 = new HashedMap();
                    map1.put("state", currencyCode.待支付.getCode());
                    waiterListDao.update(map1, waiterId);
                }
            }
        }
        return waiterListDao.queryWaiterBusinessList(businessName, typeId, address, userId, nowPage, pageSize);
    }

    /**
     * 添加本地服务商家
     *
     * @param
     * @param waiterName
     * @param waiterType
     * @param waiterAddress
     * @param star
     * @param price
     * @param listPic
     * @param picture
     * @param cityId
     * @param provincesId
     * @param regionId
     * @param lat
     * @param lng
     * @param userId
     * @param personalPic
     * @param businessPic
     * @param ifPayment
     * @param money
     * @param phone
     * @param name
     */
    @Override
    public Map<String, Object> addWaiterBusiness(String waiterName, Integer waiterType, String waiterAddress, Integer star, BigDecimal price, String listPic, String picture, String remark, Integer cityId, Integer provincesId, Integer regionId,
                                                 String lat, String lng, Integer userId, String personalPic, String businessPic, Integer ifPayment, BigDecimal money, String phone, String name) throws ServiceException {
        WaiterList waiterList = new WaiterList();
        waiterList.setWaiterName(waiterName);
        if (waiterType == 0) {
            throw new ServiceException("请选择商家分类");
        } else {
            waiterList.setWaiterType(waiterType);
        }
        waiterList.setWaiterAdress(waiterAddress);
        waiterList.setStar(star);
        waiterList.setPrice(price);
        waiterList.setListPic(listPic);
        waiterList.setPicture(picture);
        waiterList.setLng(lng);
        waiterList.setLat(lat);
        waiterList.setRemark(remark);
        if (cityId > 0) {
            //获取当前id下的信息
            City city = cityDao.getCityById(cityId);
            int a = city.getParentId().intValue();
            waiterList.setProvincesId(a);
        } else {
            throw new ServiceException("请选择城市");
        }
        waiterList.setCityId(cityId);
        waiterList.setRegionId(regionId);
        waiterList.setMinCityId(regionId);
        //是否缴费  0不缴费  免费   1缴费 但是缴费到支付页面却不缴费，还是为1
        if (ifPayment == 0) {
            waiterList.setState(currencyCode.同意申请.getCode());
        } else {
            waiterList.setState(currencyCode.申核中.getCode());
        }
        waiterList.setCreated(new Date());
        waiterList.setUserId(userId);
        waiterList.setStatus(1);
        if (personalPic.equals("")) {
            waiterList.setBusinessPic(businessPic);
        } else {
            waiterList.setPersonalPic(personalPic);
        }
        waiterList.setIfPayment(ifPayment);
        waiterList.setPhone(phone);
        waiterList.setPhoneName(name);
        waiterListDao.save(waiterList);
        //查询最新本地服务商家的id
        Map<String, Object> map = waiterListDao.getwaiterListId();
        return map;
    }

    /**
     * 修改状态
     *
     * @param id
     * @param state
     * @return
     */
    @Override
    public int updateWaiterStatus(Integer id, Integer state) {
        return waiterListDao.updateWaiterStatus(id, state);
    }

    /**
     * 查询全部商家 ， 用于地图的展示 。 返回经纬度  ， 地址  ， 名称
     *
     * @param cityid
     * @param key
     * @return
     * @throws ServiceException
     */
    @Override
    public List<Map<String, Object>> findAllCompanyAtlas(int cityid, String key) throws ServiceException {
        return waiterListDao.findAllCompanyAtlas(cityid, key);
    }

    /**
     * 查询商家详情
     *
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> queryWaiterDetails(Integer id) {
        Map<String, Object> map = waiterListDao.queryWaiterDetails(id);
        WaiterList waiterList = waiterListDao.getEntityById(id);
        User user = userDao.getEntityById(waiterList.getUserId());
        map.put("ryToken", JSONObject.fromObject(user.getRyToken()).get("token"));
        return map;
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Override
    public boolean deleteWaiter(Integer id) {
        return waiterListDao.deleteWaiter(id);
    }

    /**
     * 修改服务商家
     *
     * @param id
     * @param waiterName
     * @param waiterType
     * @param waiterAddress
     * @param price
     * @param cityId
     * @param provincesId
     * @param regionId
     * @param listPic
     * @param picture
     * @param remark
     * @param lat
     * @param lng
     * @param userId
     * @param personalPic
     * @param businessPic
     * @param ifPayment
     * @param money
     * @param payType
     * @param phone
     * @param name
     * @return
     */
    @Override
    public boolean updateWaiterService(Integer id, String waiterName, Integer waiterType, String waiterAddress, BigDecimal price, Integer cityId, Integer provincesId, Integer regionId, String listPic, String picture, String remark, String lat, String lng, Integer userId, String personalPic, String businessPic, Integer ifPayment, BigDecimal money, Integer payType, String phone, String name) {
        Map map = new HashedMap();

        map.put("waiterName", waiterName);
        map.put("waiterType", waiterType);
        map.put("waiterAdress", waiterAddress);
        map.put("phone", phone);
        map.put("price", price);
        map.put("cityId", cityId);
        City city = cityDao.getCityById(cityId);
        int a = city.getParentId().intValue();
        map.put("provincesId", a);
        map.put("regionId", regionId);
        map.put("minCityId", regionId);
        map.put("listPic", listPic);
        map.put("picture", picture);
        map.put("remark", remark);
        map.put("lat", lat);
        map.put("lng", lng);
        map.put("phoneName", name);
        if (personalPic.equals("")) {
            map.put("businessPic", businessPic);
        } else {
            map.put("personalPic", personalPic);
        }
        trendService.updateShare(id,waiterName,BigDecimal.valueOf(0),BigDecimal.valueOf(0),remark,waiterAddress,2);
//        map.put("ifPayment", ifPayment);
        return waiterListDao.update(map, id);
    }

    /**
     * 服务商家支付
     *
     * @param id
     * @param userId
     * @param payType
     * @param money   @return
     */
    @Override
    public Map<String, Object> payMentMoney(Integer id, Integer userId, Integer payType, BigDecimal money) {
        Map map = new HashedMap();
        User user = userDao.getEntityById(userId);
        String title = user.getNickName() + "付款：" + money + "元";
        String kId = "service" + KidUtils.getKKid();
        boolean isTrue = false;
        //1支付宝、2微信
        if (payType == 1) {
            //支付宝
            String aplipay = AppPay.createPay(title, kId, title, money.doubleValue());//这里传的是支付订单编号
            map.put("pay", aplipay);
        } else if (payType == 2) {
            int price = money.multiply(BigDecimal.valueOf(100)).intValue();
            map = WeixinUtils.getPayInfo(title, price, kId);
        }
        return map;
    }

    /**
     * @param id
     * @param userId
     * @param payType
     * @param money
     * @param ifPayment
     * @return
     */
    @Override
    public boolean updatePaymentMoney(Integer id, Integer userId, Integer payType, BigDecimal money, Integer ifPayment) {
        Map maps = new HashedMap();
        Map<String, Object> map = waiterListDao.getIdInfo(id);
        //如果之前是待支付，就修改为审核中
        String num = map.get("state").toString();
        if (num.equals("4")) {
            maps.put("state", currencyCode.申核中.getCode());
            waiterListDao.update(maps, id);
        }
        //修改状态  现在为支付成功
        maps.put("ifPayment", ifPayment);
        waiterListDao.update(maps, id);
        //添加记录
        CompanyPanymentHistory companyPanymentHistory = new CompanyPanymentHistory();
        companyPanymentHistory.setCreatedTime(new Date());
        companyPanymentHistory.setPaymentType(payHistory.本地生活服务.getCode());
        companyPanymentHistory.setPaymentMoney(money);
        companyPanymentHistory.setPaymentTime(1);
        companyPanymentHistory.setWaiterServiceId(id);
        companyPanymentHistory.setPayType(payType);
        companyPanymentHistory.setCompanyId(0);
        companyPanymentHistory.setCarouselId(0);
        companyPanymentHistory.setGoodId(0);
        companyPanymentHistory.setRecommendId(0);
        return companyPanymentHistoryDao.save(companyPanymentHistory) > 0;
    }

    /**
     * @param waiterName
     * @param nowPage
     * @param pageSize
     * @return
     */
    @Override
    public Page queryAuditingBus(String waiterName, int nowPage, int pageSize) {
        return waiterListDao.queryAuditingBus(waiterName, nowPage, pageSize);
    }

    /**
     * @param waiterName
     * @param address
     * @param typeId
     * @param nowPage
     * @param pageSize   @return
     */
    @Override
    public Page queryWaiterBusiness(String waiterName, String address, Integer typeId, int nowPage, int pageSize) {
        return waiterListDao.queryWaiterBusiness(waiterName, address, typeId, nowPage, pageSize);
    }

    /**
     * @param id
     * @param payTime
     * @param starWaiter
     * @return
     */
    @Override
    public int throughService(Integer id, Integer payTime, Integer starWaiter) {
        return waiterListDao.throughService(id, 2, starWaiter);
    }

    /**
     * @param id
     * @param waiterName
     * @param waiterType
     * @param price
     * @param listPic
     * @param picture
     * @param remark
     * @param star
     * @return
     */
    @Override
    public boolean update(Integer id, String waiterName, Integer waiterType, BigDecimal price, String listPic, String picture, String remark, Integer star) {
        Map map = new HashedMap();
        map.put("waiterName", waiterName);
        map.put("waiterType", waiterType);
        map.put("price", price);
        map.put("listPic", listPic);
        map.put("picture", picture);
        map.put("remark", remark);
        map.put("star", star);
        return waiterListDao.update(map, id);
    }

    /**
     * 缴费失败调用
     *
     * @param id
     * @return
     */
    @Override
    public boolean failPaymentMoney(Integer id) {
        return updateWaiterStatus(id, currencyCode.待支付.getCode()) > 0;
    }

    /**
     * @param id
     * @param status
     * @return
     */
    @Override
    public int updateStatus(Integer id, Integer status) {
        return waiterListDao.updateStatus(id, status);
    }
}
